package com.axjy.comm.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.SecretKey;
import java.util.Date;

@Component
@RefreshScope
@Slf4j
public class TokenUtil {

    @Value("${jjwt.security12:a06ac79b-b340-4635-817d-d0ec1a41bbc2}")
    private String security; //私钥,相当于验证码

    private long createTime;//创建时间

    @Value("${jjwt.ttl:20}")
    private long ttl;//持续时间

    private SecretKey secretKey;

    public long getCreateTime() {
        createTime=System.currentTimeMillis();
        return createTime;
    }

    @PostConstruct
    public void init(){
        secretKey=Keys.hmacShaKeyFor(security.getBytes());
    }

    public long getTtl(){
        return ttl;
    }

    public String createToken(Integer userId){
        String token= Jwts.builder().setId(String.valueOf(userId))
                .setIssuedAt(new Date(getCreateTime()))
                .setExpiration(new Date(getCreateTime()+getTtl()*60*1000))
                .signWith(secretKey).compact();
        System.out.println("生成token的secretkey"+new String(secretKey.getEncoded()));
        return token;
    }

    public Integer checkToken(String token){
        Integer userId=-1;
        try {
            System.out.println("验证的secretKey"+new String(secretKey.getEncoded()));
            Claims claims = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token).getBody();
            String id=claims.getId();
            userId=Integer.valueOf(id);
        }catch (Exception ex){
            ex.printStackTrace();
            log.debug(ex.getMessage());
        }
        return userId;
    }


}
